<template>
  <div id="chatPage">
    <div class="content">
      <div id="header">
        <div class="return" @click="returnClick"></div>
        <div class="title">开车聊天室</div>
        <div class="userNum">在线人数：{{ onlineLength }}</div>
      </div>
      <div id="main">
        <div class="mainContent noStyleScroll" ref="msgListCont">
          <div class="msgList" ref="msgList">
            <div class="magItem"
                 :class="{self:chatItem.type==='oneself',
                 noself:chatItem.type==='otherPeople',
                 'enter-leave':chatItem.type==='enter-leave'}"
                 v-for="(chatItem,chatIndex) in magList" :key="chatIndex">
              <template v-if="chatItem.type==='oneself'||chatItem.type==='otherPeople'">
                <div class="magItemContent flex">
                  <div class="head">
                    <img class="img" :src="chatItem.headImgUrl" alt="">
                  </div>
                  <div class="textCont flex">
                    <div class="textContMsg flex">
                      <div class="text">{{ chatItem.msg }}</div>
                    </div>
                    <div class="tip flex">
                      <div class="name">{{ chatItem.name }}</div>
                      <div class="date">{{ chatItem.sendDate }}</div>
                    </div>
                  </div>
                </div>
              </template>
              <template v-if="chatItem.type==='enter-leave'">
                <div class="text">{{ chatItem.msg }}</div>
              </template>
            </div>
          </div>
        </div>
      </div>
      <div class="control">
        <div class="controlContent flex">
          <div class="inputBox">
            <input
                @keydown.enter="inputkeydown($event)"
                type="text" v-model="inputValue"/>
          </div>
          <div class="sendBtn" @click="sendMsg"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {mapState} from 'vuex'

export default {
  name: "chatPage",
  created() {
    this.init()
  },
  data() {
    return {
      detailsState: {
        name: '',
        headImgUrl: ''
      },
      onlineLength: 0,
      inputValue: '',
      magList: []
    }
  },
  methods: {

    //初始化辅助函数
    async init() {
      this.detailsState.name = this.$route.params.name;
      this.detailsState.headImgUrl = this.$route.params.headImgUrl
      this.getMsg()
      this.join()
      this.disconnect()
      //向服务器其他用户发送一条加入消息
      this.socket.emit('join', {
        name: this.detailsState.name
      })
    },


    //发送数据
    sendMsg() {
      if (this.inputValue.length > 0) {
        let data = this.message
        this.socket.emit('send', data)
        this.magList.push(data)
        this.inputValue = ''
        // let listHeight = this.$refs.msgList.offsetHeight
        this.dropScroll()
      }
    },
    //接收数据
    getMsg() {
      console.log(this.socket)
      this.socket.on('reception', data => {
        if (data.id !== this.socketId) {
          data.type = 'otherPeople'
          data.postion = 'left'
        }
        this.magList.push(data)
        this.dropScroll()
      })

    },
    //监测加入
    join() {
      this.socket.on('join', data => {
        this.onlineLength = data.length
        this.magList.push({
          msg: `${data.name}加入了聊天室`,
          type: 'enter-leave'
        })
      })
    },
    //监测离开
    disconnect() {
      this.socket.on('close', data => {
        this.onlineLength = data.length
        this.magList.push({
          msg: `${data.name}离开了聊天室`,
          type: 'enter-leave'
        })
      })
    },


    //返回到首页
    returnClick() {
      this.$router.push({
        name: 'userRole'
      })
    },
    //获取时间
    newMagDate() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      let day = new Date().getDate();
      let hour = new Date().getHours();
      let minute = new Date().getMinutes();
      let second = new Date().getSeconds();
      return `${year}:${month}:${day}-${hour}:${minute}:${second}`
    },
    //组合键盘监控
    inputkeydown(e) {
      if (!e.ctrlKey) {
        this.sendMsg()
      }
    },
    //辅助滚动
    dropScroll() {
      this.$nextTick(() => {
        let listContHeight = this.$refs.msgListCont.offsetHeight,
            listContScrollHeight = this.$refs.msgListCont.scrollHeight;
        this.$refs.msgListCont.scrollTop = listContScrollHeight - listContHeight
      })
    },
  },
  computed: {
    ...mapState(['socket', 'socketId']),
    message() {
      return {
        name: this.detailsState.name,
        id: this.socketId,
        postion: 'right',
        type: 'oneself',
        msg: this.inputValue,
        sendDate: this.newMagDate().split('-')[1],
        headImgUrl: this.detailsState.headImgUrl
      }
    }
  }
}
</script>
<style scoped lang="less">
* {
  //border: 1px solid red;
}
#chatPage {
  width: 100%;
  height: 100%;
  @headerHeight: 40px;
  @controlHeight: 50px;
  .content {
    width: 100%;
    height: 100%;
    #header {
      width: 100%;
      height: 40px;
      position: relative;
      border-bottom: 1px solid rgba(0, 0, 0, .3);
      div {
        position: absolute;
        height: 40px;
      }
      .return {
        width: 40px;
        background: url('~@/static/return-jt.png') center center no-repeat;
        background-size: 50% 50%;
      }
      .title {
        left: 50%;
        line-height: 40px;
        font-size: 16px;
        transform: translateX(-50%);
      }
      .userNum {
        right: 10px;
        line-height: 40px;
        color: red;
      }
    }
    #main {
      width: 100%;
      height: calc(100% - @headerHeight - @controlHeight);
      overflow: hidden;
      * {
        //border: 1px solid red;
      }
      .mainContent {
        width: 100%;
        height: 100%;
        overflow-y: scroll;
        .msgList {
          width: 100%;
          .magItem {
            width: 100%;
            margin-bottom: 10px;
            .magItemContent {
              * {
                //border: 1px solid red;
              }
              align-items: flex-end;
              .head {
                width: 40px;
                height: 40px;
                margin-right: 10px;
                .img {
                  width: 40px;
                  height: 40px;
                  border-radius: 50%;
                }
              }
              .textCont {
                max-width: 200px;
                flex-direction: column;
                .textContMsg {
                  background-color: rgba(51, 51, 51, 0.2);
                  padding: 5px 5px;
                  align-items: center;
                  min-height: calc(40px - 15px);
                  display: inline;
                  .text {
                    font-size: 14px;

                  }
                }
                .tip {
                  margin-top: 5px;
                  height: 15px;
                  color: red;
                  .name {
                    margin-right: 5px;
                  }
                }
              }
            }
            &.noself {
              padding-left: 10px;
              .textCont {
                align-items: flex-start;
              }
            }
            &.self {
              padding-right: 10px;
              .magItemContent {
                flex-direction: row-reverse;
                .head {
                  margin-right: 0;
                  margin-left: 10px;
                }
                .textCont {
                  align-items: flex-end;
                }
                .tip {
                  flex-direction: row-reverse;
                  .name {
                    margin-right: 0px;
                    margin-left: 5px;
                  }
                }
              }
            }
            &.enter-leave {
              text-align: center;
              color: rgba(0, 0, 0, 0.5);
            }
          }
        }
      }
    }
    .control {
      width: 100%;
      height: 50px;
      padding: 5px 15px;
      .controlContent {
        background-color: rgba(51, 51, 51, .3);
        width: 100%;
        height: 100%;
        align-items: center;
        border-radius: 20px;
        padding-right: 5px;
        .inputBox {
          flex: 1;
          input {
            padding-left: 20px;
            font-size: 20px;
            width: 100%;
            min-height: 40px;
            background-color: rgba(0, 0, 0, 0);
          }
        }
        .sendBtn {
          width: 40px;
          height: 40px;
          background: url('~@/static/send .png') center center no-repeat;
          background-size: 60% 60%;
        }
      }

    }
  }
}
</style>